<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="缺陷编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入缺陷编码"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="缺陷名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入缺陷名称"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['quality:definition:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['quality:definition:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['quality:definition:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['quality:definition:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="definitionList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="60" align="center" fixed="left" />
      <el-table-column label="缺陷组件id" width="100" fixed="left" align="center" prop="id" v-if="false" />
      <el-table-column label="缺陷编码" align="center" prop="code" width="100" fixed="left" />
      <el-table-column label="缺陷名称" align="center" prop="name" width="200" />
      <el-table-column label="缺陷类型" align="center" prop="typeName" width="200" />
      <el-table-column label="责任部门" align="center" prop="deptName" width="100" />
      <el-table-column label="缺陷等级" align="center" prop="delName" width="200" />
      <el-table-column label="单位" align="center" prop="unit" width="100" />
      <el-table-column label="位置" align="center" prop="location" width="200" />
      <el-table-column label="扣分值" align="center" prop="deductMarks" width="100" />
      <el-table-column label="别名" align="center" prop="alias" width="200" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            style="margin-right: 9px"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['quality:definition:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['quality:definition:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改缺陷定义对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="760px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :lg="12">
            <el-form-item label="缺陷编码" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入缺陷编码"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="缺陷名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入缺陷名称"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="缺陷类型" prop="typeId">
              <el-select
                v-model="form.typeId"
                placeholder="请选择缺陷类型"
                style="width: 240px"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.id }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="缺陷等级" prop="delId">
              <el-select
                v-model="form.delId"
                placeholder="请选择缺陷等级"
                style="width: 240px"
              >
                <el-option
                  v-for="item in gradeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.id }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="责任部门" prop="deptId">
              <!-- <el-cascader
                v-model="form.deptIdArr"
                :options="departmentOptions"
                :show-all-levels="false"
                :props="{value: 'deptId', label: 'deptName'}"
                placeholder="请选择责任部门"
                style="width: 240px"
              ></el-cascader> -->
              <el-select
                v-model="form.deptId"
                placeholder="请选择责任部门"
                style="width: 240px"
                filterable
              >
                <el-option
                  v-for="item in departmentOptions"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                >
                  <span style="float: left">{{ item.deptId }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.deptName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="单位" prop="unit">
              <el-input
                v-model="form.unit"
                placeholder="请输入单位"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="扣分值" prop="deductMarks">
              <el-input
                v-model="form.deductMarks"
                placeholder="请输入扣分值"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="位置" prop="location">
              <el-input
                v-model="form.location"
                placeholder="请输入位置"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="别名" prop="alias">
              <el-input
                v-model="form.alias"
                placeholder="请输入别名"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listDefinition,
    getDefinition,
    delDefinition,
    addDefinition,
    updateDefinition,
    exportDefinition,
    listDepartment
  } from "@/api/quality/definition";
  import { listGrade } from "@/api/quality/grade";
  import { listType } from "@/api/quality/type";

  export default {
    name: "Definition",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 缺陷类型下拉框
        typeOptions: [],
        // 缺陷等级下拉框
        gradeOptions: [],
        // 责任部门下拉框
        departmentOptions: [],
        // departmentOptions2: [],
        // 缺陷定义表格数据
        definitionList: [],
        // 弹出层标题
        title: "",
        separateTitle: "",
        // 是否显示弹出层
        open: false,
        separateOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          code: undefined,
          name: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          code: [{ required: true, message: "缺陷编码不能为空", trigger: "change" }],
          name: [{ required: true, message: "缺陷名称不能为空", trigger: "change" }],
          typeId: [{ required: true, message: "缺陷类型不能为空", trigger: "change" }],
          delId: [{ required: true, message: "缺陷等级不能为空", trigger: "change" }],
          deptId: [{ required: true, message: "责任部门不能为空", trigger: "change" }]
        }
      };
    },
    created() {
      this.getTypeList();
      this.getGradeList();
      this.getDepartmentList();
      this.getList();
    },
    methods: {
      /** 查询缺陷定义列表 */
      getList() {
        this.loading = true;
        listDefinition(this.queryParams).then(response => {
          this.definitionList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 查询缺陷类型下拉框
      getTypeList() {
        listType({}).then(response => {
          this.typeOptions = response.rows;
        });
      },
      // 查询缺陷等级下拉框
      getGradeList() {
        listGrade({}).then(response => {
          this.gradeOptions = response.rows;
        });
      },
      // 查询部门下拉框
      getDepartmentList() {
        listDepartment({}).then(response => {
          // this.departmentOptions = this.getTreeData(this.handleTree(response.data, "deptId"));
          this.departmentOptions = response.data;
        });
      },
      // 递归树形
      getTreeData(treeData) {
        for (let i = 0; i < treeData.length; i++) {
          if (treeData[i].children.length === 0) {
            treeData[i].children = undefined;
          } else {
            this.getTreeData(treeData[i].children);
          }
        }
        return treeData;
      },

      // 根据子元素查询父级el-cascader，参数（子元素id，树形数据-平铺型，元素id字段名称，元素的父级id字段名称）
      // getFathersById(id, tileTreeData, propIdName = 'deptId', fPropIDName = 'parentId') {
      //   // 解析后返回的结构链
      //   const arrRes = [id];
      //   // 递归查询父级
      //   const handleDataAnalysis = (id, data) => {
      //     // 子元素数据Obj
      //     const selectData = data.filter((item, index) => item.deptId === id)[0] || {};
      //     for (let i = 0; i < data.length; i++) {
      //       // 对比的数据
      //       const contrastData = data[i];
      //       // 如果对比的数据id === 子元素的父级id，则该对比元素为子元素的父级
      //       if (contrastData[propIdName] === selectData[fPropIDName]) {
      //         // 父级id插入到结构链的最前面
      //         arrRes.unshift(contrastData[propIdName]);
      //         // 获取到父级id后，递归获取父级的父级直到顶级父级元素后，结束循环
      //         handleDataAnalysis(contrastData[propIdName], data);
      //       }
      //     }
      //   };
      //   // // 运行递归方法
      //   handleDataAnalysis(id, tileTreeData);
      //   // 返回结构链
      //   return arrRes;
      // },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 取消按钮
      separateCancel() {
        this.separateOpen = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加缺陷定义";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const definitionIds = row.id || this.ids;
        getDefinition(definitionIds).then(response => {
          this.form = response.data;
          // this.form.deptIdArr = this.getFathersById(response.data.deptId, this.departmentOptions2);
          this.open = true;
          this.title = "修改缺陷定义";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateDefinition(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addDefinition(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const definitionIds = row.id || this.ids;
        this.$confirm('是否确认删除缺陷定义编号为"' + definitionIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDefinition(definitionIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有缺陷定义数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportDefinition(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      }
    }
  };
</script>
